<template>
  <div class="place-search-panel">
    <el-autocomplete
      size="small"
      v-model="placeName"
      :fetch-suggestions="querySearchAsync"
      placeholder="输入地名搜索位置"
      @select="handleSelect"
      style="width: 100%"
      :clearable="false"
      :popper-append-to-body="false"
    ></el-autocomplete>
  </div>
</template>

<script>
export default {
  data() {
    return {
      placeName: ''
    }
  },
  methods: {
    async querySearchAsync(queryString, cb) {
      let resultArr = []
      if (queryString) {
        const searchParams = { keyWord: queryString, level: 18, mapBound: '-180,-90,180,90', queryType: 7, start: 0, count: 10 }
        const res = await this.$axios('https://api.tianditu.gov.cn/v2/search', {
          params: {
            postStr: JSON.stringify(searchParams),
            type: 'query',
            tk: 'f05b78140e12c03d46f442c71cb77550'
          }
        })
        if (res.data) {
          if (res.data.pois) {
            resultArr = resultArr.concat(
              res.data.pois.map((val) => {
                return {
                  value: val.name,
                  location: val.lonlat
                }
              })
            )
          }
          if (res.data.area && res.data.area.lonlat) {
            resultArr = resultArr.concat([
              {
                value: res.data.area.name,
                location: res.data.area.lonlat
              }
            ])
          }
        }
      }
      cb(resultArr)
    },

    handleSelect(item) {
      this.$emit('selected', { ...item })
    }
  }
}
</script>
<style lang="scss" scoped>
.place-search-panel {
  width: 100%;
  position: relative;
}
</style>
